package cn.cloudmenu.android.activity;

import java.net.URI;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.cloudmenu.android.CloudMenuApp;
import cn.cloudmenu.android.MenuCoverBean;
import cn.cloudmenu.android.MenuOpeningTableBean;
import cn.cloudmenu.android.R;
import cn.cloudmenu.android.TablesWebSocket;
import cn.cloudmenu.android.UserProfile;

public class ChooseTable extends ListActivity {
	private ArrayList<MenuOpeningTableBean> TableList = new ArrayList<MenuOpeningTableBean>();
	private TablesWebSocket webSocket;

	private class EfficientAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private Bitmap mIcon;

		public EfficientAdapter(Context context) {
			// Cache the LayoutInflate to avoid asking for a new one each time.
			mInflater = LayoutInflater.from(context);

			// Icons bound to the rows.
			mIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.table);
		}

		/**
		 * The number of items in the list is determined by the number of
		 * speeches in our array.
		 * 
		 * @see android.widget.ListAdapter#getCount()
		 */
		public int getCount() {
			return TableList.size();
		}

		/**
		 * Since the data comes from an array, just returning the index is
		 * sufficent to get at the data. If we were using a more complex data
		 * structure, we would return whatever object represents one row in the
		 * list.
		 * 
		 * @see android.widget.ListAdapter#getItem(int)
		 */
		public Object getItem(int position) {
			return TableList.get(position);
		}
		

		/**
		 * Use the array index as a unique id.
		 * 
		 * @see android.widget.ListAdapter#getItemId(int)
		 */
		public long getItemId(int position) {
			return position;
		}

		/**
		 * Make a view to hold each row.
		 * 
		 * @see android.widget.ListAdapter#getView(int, android.view.View,
		 *      android.view.ViewGroup)
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			// A ViewHolder keeps references to children views to avoid
			// unneccessary calls
			// to findViewById() on each row.
			ViewHolder holder;

			// When convertView is not null, we can reuse it directly, there is
			// no need
			// to reinflate it. We only inflate a new View when the convertView
			// supplied
			// by ListView is null.
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.tables_list_item_icon_text, null);

				// Creates a ViewHolder and store references to the two children
				// views
				// we want to bind data to.
				holder = new ViewHolder();
				holder.name = (TextView) convertView.findViewById(R.id.table_list_name);
				holder.status = (TextView) convertView.findViewById(R.id.table_list_status);
				holder.icon = (ImageView) convertView.findViewById(R.id.table_list_icon);
				holder.join = (Button) convertView.findViewById(R.id.table_list_join_button);
				holder.join.setTag(TableList.get(position));
				convertView.setTag(holder);
			} else {
				// Get the ViewHolder back to get fast access to the TextView
				// and the ImageView.
				holder = (ViewHolder) convertView.getTag();
			}

			// Bind the data efficiently with the holder.
			holder.name.setText(TableList.get(position).getOpener());
			holder.status.setText(TableList.get(position).getStatus());
			holder.icon.setImageBitmap(mIcon);

			return convertView;
		}

		class ViewHolder {
			TextView status;
			TextView name;
			ImageView icon;
			Button join;
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tables);
		try {
			System.out.println("wwwwwwwwwwwwwwwwwwwwwwww WebSocket 1");
			String websocket_url = this.getResources().getString(R.string.websocket_url);
			WebView webView = new WebView(this);
			// Integer menuId = getIntent().getIntExtra("menuId", -1);
			UserProfile user = ((CloudMenuApp) this.getApplication()).getUser();
			MenuCoverBean menu = ((CloudMenuApp) this.getApplication()).getMenu();
			this.webSocket = new TablesWebSocket(webView, URI.create(websocket_url), user, menu, this);
			webSocket.connect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void packListView(){
		System.out.println("00000000000000000000000000000000ChooseTable.packListView()");
		setListAdapter(new EfficientAdapter(this));
		final ListView listView = getListView();
		listView.setItemsCanFocus(false);
		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		// 为ListView设置列表项点击监听器
		/*
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				System.out.println(".......................ChooseTable.packListView() ItemClickListener.onItemClick()");
				MenuOpeningTableBean table = (MenuOpeningTableBean) parent.getItemAtPosition(position);
				System.out.println(".......................ChooseTable.packListView() ItemClickListener.onItemClick() table.getTableName()="+table.getTableName());
				System.out.println(".......................ChooseTable.packListView() ItemClickListener.onItemClick() table.getOpener()()="+table.getOpener());
				Intent intent = new Intent(ChooseTable.this, Categories.class);
				intent.putExtra("menuId", table.getMenuId());
				intent.putExtra("tableName", table.getTableName());
				intent.putExtra("opener", table.getOpener());
				ChooseTable.this.startActivity(intent);
			}
		});		*/
	}
	
	public void startMakingOrder(MenuOpeningTableBean table) {
		Intent intent = new Intent(this, Categories.class);
		//intent.putExtras(getIntent());
		intent.putExtra("menuId", table.getMenuId());
		intent.putExtra("tableName", table.getTableName());
		intent.putExtra("opener", table.getOpener());
		this.startActivity(intent);
	}

	public void openTable(View view) {
		this.webSocket.openTable();
	}
	
	public void refreshTableList(View view) {
		this.webSocket.tableList();
	}
	
	public void startMakingOrder(View view) {
		MenuOpeningTableBean table = (MenuOpeningTableBean)view.getTag();
		startMakingOrder(table);
	}

	private void displayMessage(String message) {
		Toast t1 = Toast.makeText(getApplication(), message, Toast.LENGTH_LONG * 2);
		t1.show();
	}

	public void setTableList(JSONArray tables) {
		TableList.clear();
		try {
			for (int i = 0; i < tables.length(); i++) {
				JSONObject table = tables.getJSONObject(i);
				System.out.println("00000000000000000000000000000000ChooseTable onMessage() command tableList table = "+ table);
				MenuOpeningTableBean tableBean = new MenuOpeningTableBean();
				TableList.add(tableBean);
				tableBean.setMenuId(table.getInt("menuId"));
				tableBean.setTableName(table.getString("tableName"));
				tableBean.setOpener(table.getString("opener"));
				tableBean.setStatus(table.getString("status"));
			}
			System.out.println("00000000000000000000000000000000ChooseTable.setTableList() TableList.size() = "+TableList.size());
			//this.packListView();
			cwjHandler.post(mUpdateResults);
		} catch (Exception e) {
			//e.printStackTrace();
			displayMessage(e.getMessage());
		}
	}
	
	final Handler cwjHandler = new Handler();

	final Runnable mUpdateResults = new Runnable() {
		public void run() {
	    	packListView();
	    }
	};
}